package com.charlie.sessions;

import com.charlie.beans.Product;
import com.charlie.beans.ShipmentOrder;
import com.charlie.beans.SoProduct;
import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Вова
 */
@Stateless
public class SoProductFacade extends AbstractFacade<SoProduct> implements SoProductFacadeLocal {

    @PersistenceContext(unitName = "CharlieShop-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public SoProductFacade() {
        super(SoProduct.class);
    }

    @Override
    public void removeProduct(Integer orderID, Integer productID) {
        try {
            System.err.print("param " + orderID + " and " + productID);

            Product pr = em.find(Product.class, productID);
            ShipmentOrder sh = em.find(ShipmentOrder.class, orderID);
            Query q = em.createQuery("Select p FROM SoProduct p WHERE p.productId =?1 AND p.soId=?2", SoProduct.class);
            q.setParameter(1, pr);
            q.setParameter(2, sh);
            SoProduct shOrder = (SoProduct) q.getSingleResult();

            if (shOrder != null) {
                em.remove(shOrder);

                em.refresh(sh);
                System.err.print("was deleted");
            } else {
                System.err.print("was not deleted");
            }
            if (pr != null) {
                System.err.println("param of prod " + pr.getProductId());
            } else {
                System.err.println("no prod");
            }
            if (sh != null) {
                System.err.println(" and order" + sh.getSoId());
            } else {
                System.err.println("no order");
            }





        } catch (NoResultException ex) {
        }

    }

    @Override
    public SoProduct updateAmountBYorderID_and_soID(Product pr, ShipmentOrder so, Integer amount) {
        SoProduct sOrder = null;
        try {
            Query q = em.createQuery("Select p FROM SoProduct p WHERE p.productId =?1 AND p.soId=?2", SoProduct.class);
            q.setParameter(1, pr);
            q.setParameter(2, so);
            sOrder = (SoProduct) q.getSingleResult();
            sOrder.setAmount(amount);
            em.persist(sOrder);
            
            return sOrder;
        } catch (NoResultException ex) {
            return sOrder;
        }

    }

    @Override
    public void addItems(Collection<SoProduct> prod) {
        for (SoProduct so : prod) {
                    em.persist(so);
                    
                }
    }
    
}
